package edu.sysu.controller;

import edu.sysu.domain.Book;
import edu.sysu.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/books")
public class BookController {

    @Autowired
    private BookService bookService;

    @PostMapping
    public Result save(@RequestBody Book book) {
        boolean flag = bookService.save(book);
        return new Result(flag ? Code.SAVE_OK : Code.SAVE_ERROR, flag);
    }
    @PutMapping
    public Result update(@RequestBody Book book) {
         boolean flag = bookService.update(book);
         return new Result(flag ? Code.UPDATE_OK : Code.UPDATE_ERROR, flag);
    }
    @DeleteMapping(value = "/{id}")
    public Result delete(@PathVariable Integer id) {
        boolean flag = bookService.delete(id);
        return new Result(flag ? Code.DELETE_OK : Code.DELETE_ERROR, flag);
    }
    @GetMapping(value = "/{id}")
    public Result getById(@PathVariable Integer id) {
        Book book = bookService.getById(id);
        if (book == null) {
            return new Result(Code.GET_ERROR, null, "没有该id的图书");
        }
        return new Result(Code.GET_OK, book, "获取成功");
    }
    @GetMapping
    public Result getAll() {
        List<Book> books = bookService.getAll();
        if (books == null) {
            return new Result(Code.GET_ERROR, null, "没有图书");
        }
        return new Result(Code.GET_OK, books, "获取成功");
    }
}
